package @{packagePath}

import (
	"cs/utils/base"
	"github.com/gogf/gf/g"
	"github.com/gogf/gf/g/database/gdb"
	"github.com/gogf/gf/g/os/glog"
	"github.com/gogf/gf/g/util/gconv"
)

type @{crud.table.className} struct {
	// columns START
	# for(column in crud.table.columns){ #
	# if(column.columnName=='enable'||column.columnName=='update_time'||column.columnName=='update_id'||column.columnName=='create_time'||column.columnName=='create_id'){ #
	# 	continue; #
	# } #
	@{strutils.toUpperCaseFirst(column.columnJavaName)}		@{strutils.toLowerCase(column.goType)} `json:"@{strutils.toLowerCaseFirst(column.columnJavaName)}" gconv:"@{strutils.toLowerCase(column.columnName)},omitempty"`  // @{column.remarks}
	# } #
	// columns END

	base.BaseModel
}

func (model @{crud.table.className}) Get() @{crud.table.className} {
	if model.Id <= 0 {
		glog.Error(model.TableName() + " get id error")
		return @{crud.table.className}{}
	}

	var resData @{crud.table.className}
	err := model.dbModel("t").Where(" id = ?", model.Id).Fields(model.columns()).Struct(&resData)
	if err != nil {
		glog.Error(model.TableName()+" get one error", err)
		return @{crud.table.className}{}
	}

	return resData
}

func (model @{crud.table.className}) GetOne(form *base.BaseForm) @{crud.table.className} {
	where := " 1 = 1 "
	var params []interface{}
	if form.Params != nil && form.Params["id"] != "" {
		where += " and id = ? "
		params = append(params, gconv.Int(form.Params["id"]))
	}

	var resData @{crud.table.className}
	err := model.dbModel("t").Where(where, params).Fields(model.columns()).Struct(&resData)
	if err != nil {
		glog.Error(model.TableName()+" get one error", err)
		return @{crud.table.className}{}
	}

	return resData
}

func (model @{crud.table.className}) List(form *base.BaseForm) []@{crud.table.className} {
    where := " 1 = 1 "
    var params []interface{}
    if form.Params != nil && form.Params["name"] != "" {
        where += " and name like ? "
		params = append(params, "%"+form.Params["name"]+"%")
    }

	var resData []@{crud.table.className}
	err := model.dbModel("t").Fields(
	    model.columns()).Where(where, params).OrderBy(form.OrderBy).Structs(&resData)
	if err != nil {
		glog.Error(model.TableName()+" list error", err)
		return []@{crud.table.className}{}
	}

	return resData
}

func (model @{crud.table.className}) Page(form *base.BaseForm) []@{crud.table.className} {
	if form.Page <= 0 || form.Rows <= 0 {
	    glog.Error(model.TableName()+" Page Param error", form.Page, form.Rows)
	    return []@{crud.table.className}{}
	}

	where := " 1 = 1 "
	var params []interface{}
	if form.Params != nil && form.Params["name"] != "" {
		where += " and name like ? "
		params = append(params, "%"+form.Params["name"]+"%")
	}

	num, err := model.dbModel("t").Where(where, params).Count()
	form.TotalSize = num
	form.TotalPage = num / form.Rows

	// 没有数据直接返回
	if num == 0 {
		form.TotalPage = 0
		form.TotalSize = 0
		return []@{crud.table.className}{}
	}

	var resData []@{crud.table.className}
	pageNum, pageSize := (form.Page-1)*form.Rows, form.Rows
	dbModel := model.dbModel("t").Fields(model.columns()+",su1.real_name as updateName,su2.real_name as createName")
	dbModel = dbModel.LeftJoin("sys_user su1"," t.update_id = su1.id ")
	dbModel = dbModel.LeftJoin("sys_user su2"," t.update_id = su2.id ")
	err = dbModel.Where(where, params).Limit(pageNum, pageSize).OrderBy(form.OrderBy).Structs(&resData)
	if err != nil {
		glog.Error(model.TableName()+" Page list error", err)
		return []@{crud.table.className}{}
	}

	return resData
}

func (model @{crud.table.className}) Delete() int64 {
	if model.Id <= 0 {
	    glog.Error(model.TableName() + " delete id error")
	    return 0
	}

	r, err := model.dbModel().Where(" id = ?", model.Id).Delete()
	if err != nil {
	    glog.Error(model.TableName()+" delete error", err)
	    return 0
	}

	res, err2 := r.RowsAffected()
	if err2 != nil {
	    glog.Error(model.TableName()+" delete res error", err2)
	    return 0
	}

	system.LogSave(model, system.DELETE)
	return res
}

func (model @{crud.table.className}) Update() int64 {
	r, err := model.dbModel().Data(model).Where(" id = ?", model.Id).Update()
	if err != nil {
		glog.Error(model.TableName()+" update error", err)
		return 0
	}

	res, err2 := r.RowsAffected()
	if err2 != nil {
		glog.Error(model.TableName()+" update res error", err2)
		return 0
	}

	system.LogSave(model, system.UPDATE)
	return res
}

func (model *@{crud.table.className}) Insert() int64 {
	r, err := model.dbModel().Data(model).Insert()
	if err != nil {
		glog.Error(model.TableName()+" insert error", err)
		return 0
	}

	res, err2 := r.RowsAffected()
	if err2 != nil {
		glog.Error(model.TableName()+" insert res error", err2)
		return 0
	} else if res > 0 {
		lastId, err2 := r.LastInsertId()
		if err2 != nil {
			glog.Error(model.TableName()+" LastInsertId res error", err2)
			return 0
		} else {
			model.Id = gconv.Int(lastId)
		}
	}

	system.LogSave(model, system.INSERT)
	return res
}

func (model @{crud.table.className})  dbModel(alias ...string) *gdb.Model {
    var tmpAlias string
    if len(alias) > 0 {
        tmpAlias = " " + alias[0]
    }
    tableModel := g.DB().Table(model.TableName() + tmpAlias).Safe()
    return tableModel
}

func (model @{crud.table.className}) PkVal() int {
	return model.Id
}

func (model @{crud.table.className}) TableName() string{
	return "@{crud.table.tableName}"
}

func (model @{crud.table.className}) columns() string{
	#
	var str = "";
	for(column in crud.table.columns){
	if(columnLP.index!=1) {
	str = str + ",";
	}
	str = str + "t." + strutils.toLowerCase(column.columnName);
	if(strutils.toLowerCase(column.columnName)!=strutils.toLowerCaseFirst(column.columnJavaName) ) {
	str = str + " as " + strutils.toLowerCaseFirst(column.columnJavaName);
	}
	}
	#
	sqlColumns := "@{str}"
	return sqlColumns
}
